﻿//-----------------------------------------------------------------------
// <copyright file="MvcApplicationRoutesExtensions.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.UI.Web.Helpers{    using System;
    using System.Globalization;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using AbstractSaaSTemplate.Application.Configuration;
    using AbstractSaaSTemplate.Application.Routing;
    using OOHM.Framework.Configuration;

    /// <summary>
    /// Extends the MvcApplication with helper methods to register routes.
    /// </summary>
    public static class MvcApplicationRoutesExtensions
    {
        /// <summary>
        /// Register all ASP.NET MVC Routes which will be used to invoke controllers and actions.
        /// </summary>
        /// <param name="application">The application that will be extended.</param>
        /// <param name="routes">The context of routes for which the routes will be loaded.</param>
        public static void RegisterAreasAndRoutes(
            this MvcApplication application,
            RouteCollection routes)
        {
            if (application == null)
            {
                throw new ArgumentNullException("application");
            }
            
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            // register all areas.
            AreaRegistration.RegisterAllAreas();

            // hack for visual studio's web server
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.js/{*pathInfo}");
            routes.IgnoreRoute("{resource}.css/{*pathInfo}");
            routes.IgnoreRoute("{resource}.png/{*pathInfo}");
            routes.IgnoreRoute("{resource}.jpg/{*pathInfo}");
            routes.IgnoreRoute("{resource}.gif/{*pathInfo}");

            // Here we register the custom routes
            RegisterRoutesForHome(routes);
            RegisterRoutesForService(routes);
            RegisterRoutesForDashboard(routes);
            RegisterRoutesForTenant(routes);
            RegisterRoutesForUser(routes);

            // THE ROUTES FOR THE ROOT AREA
            // are now registered in the Areas/RootAreaRegistration
            // this has been done to better organise the "root" area
            // which was by default being left spread in the root
            // of the application.
            RegisterRoute(
                routes,
                string.Concat("{controller}/{action}.{format}/{id}"),
                string.Empty,
                "Home",
                "Index");

            RegisterRoute(
                routes,
                string.Concat("{controller}/{action}/{id}"),
                string.Empty,
                "Home",
                "Index");

            RegisterRoute(
                routes,
                string.Concat("{area}/{controller}/{action}/{id}"),
                string.Empty,
                "Home",
                "Index");
        }

        /// <summary>
        /// Processes and include to routind data information about the tenant,
        /// identified by the request information.
        /// </summary>
        /// <param name="application">The application which will be extended.</param>
        public static void ProcessRouteDataForTenancy(this MvcApplication application)
        {
            if (application == null)
            {
                throw new ArgumentNullException("application");
            }

            // var we get the tenant's key
            var appBaseDomain = Configurator.GetConfigurationByKey<string>(ConfigurationKeys.AppBaseDomain);

            const string TenantKeyPlaceHolder = "--key--";
            var placeHolderedDomain = string.Format(
                CultureInfo.InvariantCulture,
                appBaseDomain,
                TenantKeyPlaceHolder);

            var pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;

            var tenantKey = string.Empty;
            if (placeHolderedDomain.StartsWith(TenantKeyPlaceHolder, StringComparison.OrdinalIgnoreCase))
            {
                tenantKey = HttpContext.Current.Request.Url.Authority;
            }
            else if (!string.IsNullOrWhiteSpace(pathAndQuery))
            {
                var frags = pathAndQuery.Split(
                    new[] { '/' },
                    StringSplitOptions.RemoveEmptyEntries);

                tenantKey = frags.FirstOrDefault();
            }

            // if no key was found, we do not try to load the tenant
            if (string.IsNullOrWhiteSpace(tenantKey))
            {
                return;
            }

            // retrieves the tenant from the repository
            var activeTenant = application.RepositoryForTenancy.GetTenantByKey(tenantKey);

            // loads all info for the routing data
            var tokens = HttpContext.Current.Request.RequestContext.RouteData.DataTokens;
            if (tokens != null)
            {
                if (tokens.ContainsKey(DataTokens.ActiveTenant))
                {
                    tokens.Remove(DataTokens.ActiveTenant);
                }

                tokens.Add(DataTokens.ActiveTenant, activeTenant);
            }
        }

        #region Custom Routes Registration

        /// <summary>
        /// Register all routes related to the controller 'Home'
        /// </summary>
        /// <param name="routes">The routes registration context.</param>
        private static void RegisterRoutesForHome(RouteCollection routes)
        {
            RegisterRoute(
                routes,
                string.Concat("pagina-inicial"),
                string.Empty,
                "Home",
                "Index");

            RegisterRoute(
                routes,
                string.Concat("home"),
                string.Empty,
                "Home",
                "Index");

            RegisterRoute(
                routes,
                string.Concat("sobre-a-empresa"),
                string.Empty,
                "Home",
                "AboutUS");

            RegisterRoute(
                routes,
                string.Concat("about-us"),
                string.Empty,
                "Home",
                "AboutUS");
        }

        /// <summary>
        /// Register all routes related to the controller 'Member'
        /// </summary>
        /// <param name="routes">The routes registration context.</param>
        private static void RegisterRoutesForUser(RouteCollection routes)
        {
            RegisterRoute(
                routes,
                string.Concat("conectar"),
                string.Empty,
                "User",
                "LogOn");

            RegisterRoute(
                routes,
                string.Concat("connect"),
                string.Empty,
                "User",
                "LogOn");

            RegisterRoute(
                routes,
                string.Concat("gerenciamento-de-usuarios"),
                string.Empty,
                "User",
                "ListUsers");

            RegisterRoute(
                routes,
                string.Concat("users-management"),
                string.Empty,
                "User",
                "ListUsers");

            RegisterRoute(
                routes,
                string.Concat("gerenciamento-de-usuarios"),
                string.Empty,
                "User",
                "CreateOrEdit");

            RegisterRoute(
                routes,
                string.Concat("users-management"),
                string.Empty,
                "User",
                "CreateOrEdit");
        }

        /// <summary>
        /// Register all routes related to the controller 'Tenant'
        /// </summary>
        /// <param name="routes">The routes registration context.</param>
        private static void RegisterRoutesForTenant(RouteCollection routes)
        {
            RegisterRoute(
                routes,
                string.Concat(string.Empty, "gerenciamento-de-licenciados"),
                string.Empty,
                "Tenant",
                "ListTenants");

            RegisterRoute(
                routes,
                string.Concat(string.Empty, "tenants-management"),
                string.Empty,
                "Dashboard",
                "ListTenants");

            RegisterRoute(
                routes,
                string.Concat(string.Empty, "edicao-de-licenciados/{id}"),
                string.Empty,
                "Tenant",
                "CreateOrEditTenant");

            RegisterRoute(
                routes,
                string.Concat(string.Empty, "tenants-maintenance/{id}"),
                string.Empty,
                "Dashboard",
                "CreateOrEditTenant");
        }

        /// <summary>
        /// Register all routes related to the controller 'Dashboard'
        /// </summary>
        /// <param name="routes">The routes registration context.</param>
        private static void RegisterRoutesForDashboard(RouteCollection routes)
        {
            RegisterRoute(
                routes,
                string.Concat(string.Empty, "painel-de-controle"),
                string.Empty,
                "Dashboard",
                "Index");

            RegisterRoute(
                routes,
                string.Concat(string.Empty, "dashboard"),
                string.Empty,
                "Dashboard",
                "Index");
        }

        /// <summary>
        /// Register all routes related to the controller 'Service'
        /// </summary>
        /// <param name="routes">The routes registration context.</param>
        private static void RegisterRoutesForService(RouteCollection routes)
        {
            RegisterRoute(
                routes,
                string.Concat("comecar-ja"),
                string.Empty,
                "Service",
                "Index");

            RegisterRoute(
                routes,
                string.Concat("join-now"),
                string.Empty,
                "Service",
                "Index");

            RegisterRoute(
                routes,
                string.Concat("pre-registro"),
                string.Empty,
                "Service",
                "PreRegister");

            RegisterRoute(
                routes,
                string.Concat("pre-register"),
                string.Empty,
                "Service",
                "PreRegister");
        }

        #endregion

        /// <summary>
        /// Registers an aera for the AreaRegistration module.
        /// </summary>
        /// <param name="routes">The routes registration context.</param>
        /// <param name="routeExpression">The expression which will be registered as route.</param>
        /// <param name="areaName">The name of the area.</param>
        /// <param name="defaultControllerName">The name of the controller.</param>
        /// <param name="defaultActionName">The name of the action.</param>
        private static void RegisterRoute(
            RouteCollection routes,
            string routeExpression,
            string areaName,
            string defaultControllerName,
            string defaultActionName)
        {
            // defines the namespace for the controllers
            const string ControllersNamespaces = "AbstractSaaSTemplate.UI.Web.Controlleres";

            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            if (string.IsNullOrWhiteSpace(routeExpression))
            {
                throw new ArgumentNullException("routeExpression");
            }

            if (string.IsNullOrWhiteSpace(defaultControllerName))
            {
                throw new ArgumentNullException("defaultControllerName");
            }

            if (string.IsNullOrWhiteSpace(defaultActionName))
            {
                throw new ArgumentNullException("defaultActionName");
            }

            if (areaName == null)
            {
                areaName = string.Empty;
            }

            var routeKey = string.Concat(
                areaName,
                "_",
                defaultControllerName,
                "_",
                defaultActionName,
                "-",
                Guid.NewGuid());

            var routeData = new
            {
                @area = areaName,
                @controller = defaultControllerName,
                @action = defaultActionName,
                @id = UrlParameter.Optional
            };

            routes.MapRoute(
                routeKey,
                routeExpression,
                routeData,
                new[] { ControllersNamespaces });
        }
    }
}


